package com.xinxing.city.recovery.utils;

import android.content.Context;
import android.speech.tts.TextToSpeech;
import android.speech.tts.UtteranceProgressListener;
import android.util.Log;

import java.util.HashMap;
import java.util.Locale;

public class TextToSpeechManager implements TextToSpeech.OnInitListener {
    private TextToSpeech tts;
    private Context context;
    private String text;

    public String play = "";

    public TextToSpeechManager(Context context, String textc) {
        this.context = context;
        tts = new TextToSpeech(context, this);
        text = textc;
    }

    @Override
    public void onInit(int status) {
        if (status == TextToSpeech.SUCCESS) {
            int result = tts.setLanguage(Locale.CHINA);

            if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                Log.e("TTS", "Language not supported");
            } else {
                // 文字转语音引擎初始化成功
                playText(text);
            }
        } else {
            Log.e("TTS", "Initialization failed");
        }
    }

    public void playText(String text) {
        Log.e("TTS","play text   " +text);
        // 设置播放参数
        HashMap<String, String> params = new HashMap<>();
        long timestamp = System.currentTimeMillis();
        params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "utteranceId"+timestamp);

        // 设置播放监听器
        tts.setOnUtteranceProgressListener(new UtteranceProgressListener() {
            @Override
            public void onStart(String utteranceId) {
                // 播放开始时的回调
                play = "playing";
            }

            @Override
            public void onDone(String utteranceId) {
                // 播放完成时的回调
                play = "stop";
            }

            @Override
            public void onError(String utteranceId) {
                // 播放错误时的回调
            }
        });

        // 开始播放文本转换的语音
        tts.setSpeechRate(.9f);
        tts.speak(text, TextToSpeech.QUEUE_FLUSH, params);
    }

    public void destroy() {
        if (tts != null) {
            tts.stop();
            tts.shutdown();
        }
    }
}
